package com.UdpRecieve.framework.jedis;


import com.UdpRecieve.tool.Global;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class JedisComponent {

    @Autowired
    JedisPool jedisPool;

    public boolean set(String key, String val) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.set(key, val).equalsIgnoreCase("OK");
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    /**
     *
     * @param key
     * @param time 超时时间单位是秒
     * @return
     */
    public Long expire (String key,Integer time){
        Jedis jedis = null;
        try {
            if (time==null){
                time = Integer.valueOf(Global.getSessionRunTime());
            }
            jedis = jedisPool.getResource();
            return jedis.expire(key, time);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    public String get(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(key);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    public Long delete(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.del(key);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    public boolean exists(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.exists(key);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

}
